//
//  DayReturnDetailViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2018/12/10.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit

class DayReturnDetailViewController: UIViewController {
    
    struct Cell {
        let type: String
        let title: String
        let subtitle: String
    }

    @IBOutlet weak var payTable: UITableView!
    
    @IBOutlet weak var detailTable: UITableView!
    
    @IBOutlet weak var alertIcon: UIImageView!
    
    @IBOutlet weak var returnLabel: MyLabel!
    
    @IBOutlet weak var submitButton: UIButton!
    
    @IBOutlet weak var descriptionLabel: UILabel!
    
    @IBOutlet weak var moneyLabel: UILabel!
    
    @IBOutlet var paySwith: PaySwith!
    
    var orderId: String?
    
    private var detail: Order.DailyFeeDetail?
    
    private var data = [Cell]() {
        didSet {
            detailTable.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        paySwith.addObserve { [weak self] payment, success in
            switch payment {
            case .wePay:
                if success {
                    XHProgressHUD.showSuccess("支付成功")
                    self?.performSegue(withIdentifier: "shareSegue", sender: nil)
                } else {
                    XHProgressHUD.showError("你已取消支付")
                }
            case .aliPay:
                if success {
                    XHProgressHUD.showSuccess("支付成功")
                    self?.performSegue(withIdentifier: "shareSegue", sender: nil)
                } else {
                    XHProgressHUD.showError("你取消了支付")
                }
            case .balance, .ticket:
                break
            }
        }
        
        guard let orderId = orderId else {
            showError("订单号错误")
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.dailyFeeDetail(orderId: orderId, success: { [weak self] detail in
            JZLoading.hideLoading()
            
            guard let self = self, let detail = detail else {
                return
            }
            
            self.returnLabel.text = self.slipViewController?.config?.dayRightInstruction
            
            self.detail = detail
            
            switch detail.isNeedPay {
            case 0: //无需支付
                self.submitButton.isHidden = false
                self.submitButton.setTitle("确认", for: .normal)
                
                self.descriptionLabel.text = "待支付金额"
            case 1: //需要支付
                self.payTable.isHidden = false
                self.submitButton.isHidden = false
                
                self.descriptionLabel.text = "待支付金额"
            case 2: //有退款
                self.alertIcon.isHidden = false
                self.returnLabel.isHidden = false
                self.submitButton.isHidden = false
                self.submitButton.setTitle("确认", for: .normal)
                
                self.descriptionLabel.text = "退款金额"
            case 3: //退款中
                self.alertIcon.isHidden = false
                self.returnLabel.isHidden = false
                
                self.descriptionLabel.text = "退款金额"
            default: break
            }
            
            self.moneyLabel.text = detail.payableAmount
            
            var cells = [Cell]()
            cells.append(Cell(type: "groundCell", title: "订单总金额", subtitle: detail.totalAmountData.totalAmount))
            cells.append(Cell(type: "cell", title: "租金总额", subtitle: detail.totalAmountData.rentAmount))
            cells.append(Cell(type: "cell", title: "不计免赔", subtitle: detail.totalAmountData.noDeductibles))
            cells.append(Cell(type: "cell", title: "整备费", subtitle: detail.totalAmountData.prepareAmount))
            cells.append(Cell(type: "cell", title: "还车附加费", subtitle: detail.totalAmountData.returnAmount))
            cells.append(Cell(type: "cell", title: "燃油费及附加", subtitle: detail.totalAmountData.oilAmount))
            
            if detail.isOilPay == 2 {
                cells.append(Cell(type: "redCell", title: "燃油费退款需要线下现场核实后再退至您的账户余额中", subtitle: ""))
            }
            
            cells.append(Cell(type: "lineCell", title: "", subtitle: ""))
            
            cells.append(Cell(type: "groundCell", title: "已付金额", subtitle: detail.paidAmountData.prepayAmount))
            cells.append(Cell(type: "cell", title: "租金", subtitle: detail.paidAmountData.rentAmount))
            cells.append(Cell(type: "cell", title: "不计免赔", subtitle: detail.paidAmountData.prepareAmount))
            cells.append(Cell(type: "cell", title: "整备费", subtitle: detail.paidAmountData.noDeductibles))
            
            self.data = cells
            
            if self.detail?.balanceFlag == 0 {
                self.paySwith.balance = false
                self.payTable.reloadData()
                
                self.payTable.snp.makeConstraints { (make) -> Void in
                    make.height.equalTo(100)
                }
            }
        }) { [weak self] msg in
            JZLoading.hideLoading()
            
            self?.showError(msg)
        }
    }

    @IBAction func submit(_ sender: UIButton) {
        guard let sn = detail?.ordersn else {
            showError("订单号错误")
            return
        }

        func pay() {
            guard let payment = paySwith.selected else {
                showError("请选择支付方式")
                return
            }
            
            guard let loc = userLocation else {
                showError("未获得经纬度")
                return
            }
            
            JZLoading.showLoadingWith(toView: self.view)
            Order.prepayPay(orderSn: sn, payment: payment, location: loc, couponSn: nil, success: { [weak self] data in
                JZLoading.hideLoading()
                guard let self = self else {
                    return
                }
                
                if data?.payStatus == 2 {
                    XHProgressHUD.showSuccess("支付成功")
                    self.performSegue(withIdentifier: "shareSegue", sender: nil)
                    return
                }
                
                if let payStr = data?.payStr {
                    if payment.rawValue == 1 {
                        Pay.zhifuPay(payStr: payStr)
                    } else if payment.rawValue == 2 {
                        Pay.wechatPay(payStr: payStr)
                    } else if payment.rawValue == 4 {
                        Pay.applePay(payStr: payStr, controller: self)
                    }
                }
            }) { [weak self] msg in
                if msg.code == 2011 {
                    self?.navigationController?.popToRootViewController(animated: true)
                } else {
                    JZLoading.hideLoading()
                    self?.showError(msg)
                }
            }
        }
        
        func confim() {
            JZLoading.showLoadingWith(toView: self.view)
            Order.prepayPay(orderSn: sn, couponSn: nil, success: { data in
                JZLoading.hideLoading()
                self.navigationController?.popToRootViewController(animated: true)
            }) { [weak self] msg in
                if msg.code == 2011 {
                    self?.navigationController?.popToRootViewController(animated: true)
                } else {
                    JZLoading.hideLoading()
                    self?.showError(msg)
                }
            }
        }
        
        if let p = detail?.isNeedPay {
            switch p {
            case 0: //无需支付
                confim()
            case 1: //需要支付
                pay()
            case 2: //有退款
                confim()
            default: break
            }
        }
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "shareSegue" {
            if let vc = segue.destination as? ShareViewController {
                vc.orderId = orderId
            }
        }
    }
}

extension DayReturnDetailViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = data[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: item.type, for: indexPath)
        
        if item.type == "groundCell" || item.type == "cell" {
            cell.textLabel?.text = item.title
            cell.detailTextLabel?.text = item.subtitle
        } else if item.type == "redCell" {
            cell.textLabel?.text = item.title
        }
        
        return cell
    }
}
